package com.sinevil.tcpTrans.entity.task;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @Classname Task
 * @Description TODO
 * @Version 1.0.0
 * @Date 2025/1/5 15:12
 * @Created by sinevil
 */
public abstract class Task implements Comparable<Task> {
    /**
     * 任务优先级
     */
    protected int priority;

    /**
     * 将要发送的字节
     */
    protected ByteBuffer bytes;
    // 指令任务优先级设为1，数值越小优先级越高，这里表示指令优先级最高
    public Task(int priority) {
        this.priority = priority;
    }

    public int getPriority() {
        return priority;
    }

    public Task renewPriority(int p){
        this.priority = p;
        return this;
    }

    public ByteBuffer getBytes() {
        return bytes;
    }

    /**
     * 将字符串转化为字节数值
     * 并加上特定的头尾
     * @return
     */
    public ByteBuffer transToBytes(String str){
//        return ByteBuffer.wrap(str.getBytes(StandardCharsets.UTF_8));
        return ByteBuffer.wrap(("%${j" + str + "j}$%").getBytes(StandardCharsets.UTF_8));
    }

    @Override
    public int compareTo(Task other) {
        // 按照优先级进行比较，优先级高的排在前面（数值越大优先级越高）
        int result = Integer.compare(other.getPriority(), this.priority);
        if (result == 0)
            return -1;
        return result;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass()!= o.getClass()) return false;
        Task task = (Task) o;
        return priority == task.priority;
    }

    @Override
    public int hashCode() {
        return Objects.hash(priority);
    }


}